# -*- coding: utf-8 -*-
import requests
from app.utils import wrapper_signature

_config = {
    'connection_timeout': 30,  # 链接超时为时间为2s
    'connection_retries': 3,  # 链接重试次数为3次
    'breadtrip_host': 'http://vacationdev.breadtrip.com:8002'  # breadtrip_url = 'api.breadtrip.com'
}


def __get_session():
    '''失败进行retry.只适用于GET请求'''
    session = requests.Session()
    # print dir(session)
    session.mount("http://", requests.adapters.HTTPAdapter(max_retries=_config['connection_retries']))
    session.mount("https://", requests.adapters.HTTPAdapter(max_retries=_config['connection_retries']))
    return session


def __return_wrapper(resp):
    if resp.status_code != 200:
        return None, resp
    ret = resp.json() if resp.text != '' else {}
    return ret, resp


def _get(url, params=None, headers=None):
    try:
        s = __get_session()
        r = s.get(url, params=params, headers=headers, timeout=_config['connection_timeout'])
        s.close()
    except Exception as e:
        return None, str(e)
    return __return_wrapper(r)


def _post(url, files, data, headers=None):
    try:
        r = requests.post(
            url,
            files=files,
            data=data,
            headers=headers,
            timeout=_config['connection_timeout']
        )
    except Exception as e:
        return None, str(e)
    return __return_wrapper(r)


class BreadtripApi(object):
    """文档地址：http://gitlab.breadtrip.com:1280/shenzhen/vacation_travel_service/wikis/breadtrip-api"""

    def __init__(self):
        pass

    def get(self, path, params=None, headers=None):
        _url = _config['breadtrip_host'] + path
        return _get(_url, params, headers)

    def post(self, path, data, headers=None, files=None):
        _url = _config['breadtrip_host'] + path
        return _post(_url, files, data, headers)

    def check_login(self, sessionid):
        """通过cookie获取用户信息"""
        return self.get('/accounts/check_login/',
                        {'session_id': sessionid})

    def get_user_infos(self, user_ids):
        """批量获取用户信息, user_ids用逗号隔开"""
        _params = {'user_ids': user_ids}
        return self.get('/users/detail/', wrapper_signature(_params))

    def upload_image(self, image):
        """上传照片到七牛服务器"""
        files = {"image": image}
        result = self.post(
            '/upload/image/',
            files=files,
            data=wrapper_signature(files)
        )
        return result

    def get_poi(self, id):
        """ 获取指定poi信息
        :param id: poi id
        :return:
        """
        _params = {'id': id}
        url = '/tinysites/v2/sites/5/%s/' % id
        return self.get(url, wrapper_signature(_params))


btapi = BreadtripApi()
